<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户表相关操作
 */
class User extends Auth_Controller{

    public function __construct() {
        parent::__construct();
		if($this->session->userdata('group') != 1){
			show_404();
			exit;
		}
        $this->load->model('user_mdl');
    }

    /**
     * 用户资料验证
     */
    private function validation($data){
        if(isset($data['username'])){
            if(!$this->user_mdl->is_verify(array('username'=>$data['username']))) return '用户名已经存在';
            if(mb_strlen($data['username'],'utf-8') < 5 || mb_strlen($data['username'],'utf-8') > 20) return '用户名字符应该在5-20位之间';
            if(!preg_match("/^[0-9a-zA-Z_]{5,20}$/",$data['username'])) return '用户名只能为字母、数字和下划线';
        }
        if(isset($data['password'])){
            if(!preg_match("/^[0-9a-zA-Z_]{5,20}$/",$data['password'])) return '密码只能为字母、数字和下划线，并且在5-20位之间';
        }
        if(isset($data['mail'])){
            if(!preg_match("/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/",$data['mail'])) return '请填写正确的邮箱格式';
        }
        if(isset($data['nickname'])){
            $value = ltrim($data['nickname']);
            if(empty($value)) return '用户昵称不能为空';
        }
        return true;
    }

    /**
     * 密码修改
     */
    public function edit_pwd(){
        $post = $this->input->post(NULL,TRUE);

        if(!empty($post) && $this->input->is_ajax_request()){

            if($post['password2'] != $post['password1']){
                echo '两次密码输入不一致！';
                exit;
            }

            if(empty($post['password'])){
                echo '原密码不能为空！';
                exit;
            }

            if(!preg_match("/^[0-9a-zA-Z]{5,20}$/",ltrim($post['password2']))){
                echo '密码的长度为5-20位，不能为空';
                exit;
            }

            $data = array(
                'id' => $this->session->userdata('id'),
                'password' => md5($post['password'])
            );
            if(!$this->user_mdl->is_verify($data)){
                echo '原密码不匹配';
                exit;
            }

            $userdata = array(
                'password' => md5(ltrim($post['password2'])),
                'id' => $this->session->userdata('id')
            );
            if($this->user_mdl->edit_pwd($userdata)){
            	$this->logs->add(1,'密码修改成功！');
                $this->session->unset_userdata('username');
                echo 1;
            }else{
                echo '服务器错误！修改失败！';
            }

        }else{
            $this->_view('admin/user_edit_pwd');
        }
    }

    /**
     * 用户数据修改
     */
    public function set_user(){
        $post = $this->input->post(NULL,TRUE);
        if(!empty($post) && $this->input->is_ajax_request()){
            $v = $this->validation($post);
            if($v !== true){
                echo $v;
                exit;
            }
            if(empty($post['id'])){
                $post['id'] = $this->session->userdata('id');
            }
            $v = $this->user_mdl->edit_pwd($post);

            echo $v === false ? '服务器错误！修改失败！' : 1 ;

        }else{
            $uid = $this->input->get('uid',TRUE);
            if(empty($uid)){
                $uid = $this->session->userdata('id');
            }

            $res = $this->user_mdl->get_one($uid);
            $data['res_user'] = $res;
            $this->_view('admin/user_set_user',$data);
        }
    }
	
	/**
	 * 用户列表
	 */
	public function index(){
		
		//查询条件
		$tmp = array('group !='=>1);
		
		$get_tmp = $this->input->get('tmp',TRUE);
		$get_key = $this->input->get('keywords',TRUE);
		
		$this->db->start_cache();
		if($get_tmp == 1){
			$this->db->like('username',$get_key);
		}
		
		if($get_tmp == 2){
			$this->db->like('mail',$get_key);
		}
		
		if($get_tmp == 3){
			$this->db->like('nickname',$get_key);
		}
		$this->db->stop_cache();
		
		$this->load->library('pagination');
		$config['base_url'] = site_url('admini/user/index');
		$config['total_rows'] = $this->user_mdl->get_count($tmp);
		$config['per_page'] = 10;
		$config['page_query_string'] = TRUE;
		$config['first_link'] = '首页';
		$config['last_link'] = '尾页';
		$config['next_link'] = '下一页';
		$config['prev_link'] = '上一页';
		$config['anchor_class'] = 'current';
		
		//分页
		$this->pagination->initialize($config);
		$page = $this->pagination->create_links();
		
		//信息查询
		$list = $this->user_mdl->get_page($config['per_page'],$tmp);
		$this->db->flush_cache();
		//$list = $this->user_mdl->get_all(['group !='=>1]);
		
		$this->_view('admin/user_index',array('list'=>$list,'page'=>$page));
	}
	
	/**
	 * 修改用户状态
	 */
	public function edit_sta(){
		if(!$this->input->is_ajax_request()){
			show_404();
			exit;
		}
		
		$post = $this->input->post(NULL,TRUE);
		
		if(empty($post)){
			echo '内部错误！';
			exit;
		}
		
		$data = array(
            'id' => $post['uid'],
            'group' => $post['status']
            );
		
		$r = $this->user_mdl->edit_pwd($data);
		
		$this->logs->add($r,'修改用户状态');
		
		echo $r === false ? '修改状态失败！' : 1 ;
	}
	
	/**
	 * 操作用户
	 */
	public function create(){
		if($this->input->is_ajax_request()){
			$post = $this->input->post(NULL,TRUE);
			
			$data = array(
                'username' => $post['username'],
                'nickname' => $post['nickname'],
                'mail' => $post['mail'],
                'create_time' => $_SERVER['REQUEST_TIME'],
                'updata_time' => $_SERVER['REQUEST_TIME'],
                'group' => 2
                );
			
			if($post['password1'] == $post['password2']){
				$data['password'] = $post['password1'];
			}else{
				die('密码不一致！');
			}
			
			$v = $this->validation($data);
			
			if($v === true){
				$r = $this->user_mdl->create($data);
				$this->logs->add($r,"新增用户：",$data['username']);
				echo $r === false ? '添加用户失败！' : 1 ;
			}else{
				echo $v;
			}
			
		}else{
			$this->_view('admin/user_create');
		}
	}

}